import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:oktoast/oktoast.dart';
import '../../utils/LogUtils.dart';
import '../../utils/constants.dart';
import '../../utils/sp_utils.dart';
import '../personal/personal_page.dart';
import '../personal/personal_vm.dart';

/// 修改用户昵称页面
class SaveusernamePage extends StatefulWidget {
  final String deviceName;

  const SaveusernamePage({super.key, required this.deviceName});

  @override
  State<StatefulWidget> createState() {
    return _SaveusernamePageState();
  }
}

class _SaveusernamePageState extends State<SaveusernamePage> {
  // 获取类
  PersonViewModel viewModel = PersonViewModel();
  final TextEditingController _titlesave = TextEditingController(text: "");
  late String _deviceId;
  late String _deviceName;

  @override
  void initState() {
    super.initState();
    _deviceName = widget.deviceName;
    _titlesave.text = _deviceName;

    _titlesave.addListener(_onTextChanged);

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));
  }

  @override
  void dispose() {
    _titlesave.removeListener(_onTextChanged);
    super.dispose();
  }

  // 修改用户昵称
  Future<bool> saveusername(String data) async {
    dynamic callback = await Api.instance.saveusername(username: data);
    if (callback is bool) {
      return callback;
    } else {
      return true;
    }
  }

  Future<bool> _onWillPop() async {
    PersonalPageState.globalKeythere.currentState?.reloadData();
    return true; // 返回true表示允许返回，返回false表示阻止返回
  }

  void _onTextChanged() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: _onWillPop,
        child: Scaffold(
          backgroundColor: Color(0xFFF2F3F5),
          appBar: AppBar(
            leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () {
                _onWillPop();
                Navigator.of(context).pop();
              },
            ),
            automaticallyImplyLeading: false,
            title: Text(
              "修改用户昵称",
              style: TextStyle(
                fontSize: 17,
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w600,
              ),
            ),
            centerTitle: true,
            actions: [
              TextButton(
                child: Text(
                  "保存",
                  style: TextStyle(
                    color: Colors.green,
                    fontSize: 16,
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w600,
                  ),
                ),
                onPressed: () async {
                  if (_titlesave.text == null || _titlesave.text.isEmpty) {
                    showToast("请输入昵称");
                  } else {
                    saveusername(_titlesave.text).then((value) => {
                          if (value)
                            {
                              LogUtils.w("昵称成功"),
                              showToast("修改昵称成功"),
                              setState(() async {

                                await SpUtils.saveString(Constants.SP_USER_NAME,
                                    _titlesave.text ?? "");
                                // 单项数据流 - 从父组件过来 - 必须从父组件修改
                                viewModel.initData();

                                Navigator.of(context).pop();

                                PersonalPageState.globalKeythere.currentState
                                    ?.reloadData();
                              }),
                            }
                        });
                  }
                },
              ),
            ],
          ),
          body: SingleChildScrollView(
            child: Container(
              child: Padding(
                padding: EdgeInsets.all(16), // 添加内边距
                child: TextField(
                  controller: _titlesave,
                  decoration: InputDecoration(
                    hintText: "在此设置用户昵称",
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10), // 设置圆角半径
                      borderSide: BorderSide.none, // 去除边框线
                    ),
                    filled: true,
                    // 启用背景填充
                    fillColor: Colors.white,
                    // 设置背景颜色为白色
                    suffixIcon: _titlesave.text.isNotEmpty
                        ? IconButton(
                            icon: Icon(Icons.clear),
                            onPressed: () {
                              setState(() {
                                _titlesave.clear();
                              });
                            },
                          )
                        : null,
                    contentPadding: EdgeInsets.symmetric(
                        vertical: 0, horizontal: 15), // 设置内容内边距
                  ),
                  cursorColor: Color(0xFF00c888),
                ),
              ),
            ),
          ),
        ));
  }
}
